package com.thomasgustavo.meugood;

import java.util.ArrayList;
import java.util.List;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class Preferencias {
	
	private SharedPreferences sharedPref;

	public Preferencias(SharedPreferences sharedPref) {
		this.sharedPref = sharedPref;
	}

	public List<Cartao> lst() {
		List<Cartao> result = new ArrayList<Cartao>();
		
		String strCartoes = sharedPref.getString("cartoes", null);
		if(strCartoes != null ){
			
			String[] cartoes = strCartoes.split("\\|");
			String[] cpfs = sharedPref.getString("cpfs", null).split("\\|");
			
			for( int i = 0; i < cartoes.length; i++ ){
				if( !cartoes[i].equals("") ){
					result.add(new Cartao(cartoes[i], cpfs[i]));
				}
			}
		}
		
		return result;
	}
	
	public void add(Cartao cartao){
		String cartoes = sharedPref.getString("cartoes", null);
		String cpfs = sharedPref.getString("cpfs", null);
		
		if( cartoes == null ){
			cartoes = cartao.getNro();
			cpfs = cartao.getCpf();
		} else {
			cartoes += "|" + cartao.getNro();
			cpfs += "|" + cartao.getCpf();
		}
		
		
		Editor editor = sharedPref.edit();
		editor.putString("cartoes", cartoes);
		editor.putString("cpfs", cpfs);
		editor.commit();
	}
	
	public void del(String nro){
		List<Cartao> lst = lst();
		
		clear();
		
		for( Cartao cartao : lst ){
			if( !cartao.getNro().equals(nro) ){
				add(cartao);
			}
		}
	}
	
	public Cartao get(String nro){
		List<Cartao> lst = lst();
		
		for( Cartao cartao : lst ){
			if( cartao.getNro().equals(nro) ){
				return cartao;
			}
		}
		
		return null;
	}

	private void clear() {
		Editor editor = sharedPref.edit();
		editor.remove("cartoes");
		editor.remove("cpfs");
		editor.commit();
	}
}